import React, { useEffect, useState } from 'react'
import styles from "../sass/helpParseTable.module.scss"
import ReactQuill from "../component/richFile"
import { Button, Collapse, message, Modal, Popover, Table } from 'antd';
import { MenuFoldOutlined, MenuUnfoldOutlined } from '@ant-design/icons'
import { setResultValue } from '../reducer/parseResult';
import { useDispatch, useSelector } from 'react-redux';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import parseService from "../service/parseResult/parseResultService"
import { idText } from 'typescript';
export default function HepParseTable(this: any, props: any) {

    const { Panel } = Collapse;
    const { confirm } = Modal
    const { data, projectId, errorList } = props
    const dispatch = useDispatch()
    const [isEditTitle, setisEditTitle] = useState("")
    const keys = ["会计政策变更", "会计估计变更", "前期差错更正",
        "合并财务报表范围", "合并财务报表范围变更",
        ["货币资金", "货币资金分类明细|货币资金-货币资金分类明细", "受限货币资金|货币资金-受限货币资金"],
        ["应收账款", "应收账款坏账准备计提|应收账款-应收账款坏账准备计提", "应收账款账龄|应收账款-应收账款账龄", "应收账款前五名|应收账款-应收账款前五名"],
        ["预付款项", "预付账款账龄|预付款项-预付款项账龄", "预付账款前五名|预付款项-预付款项前五名"],
        ["其他应收款", "其他应收款坏账准备计提|其他应收款-其他应收款坏账准备计提", "其他应收款账龄|其他应收款-其他应收款账龄", "其他应收款前五名|其他应收款-其他应收款前五名"],
        ["存货", "存货明细|存货-存货明细", "存货中开发成本明细|存货-存货中开发成本明细", "存货减值明细|存货-存货减值明细", "其他流动资产明细"],
        ["可供出售金融资产", "可供出售金融资产明细|可供出售金融资产-可供出售金融资产明细", "可供出售金融资产减值明细|可供出售金融资产-可供出售金融资产减值明细"],
        ["长期股权投资", "长期股权投资明细|长期股权投资-长期股权投资明细"],
        ["长期应收款", "长期应收款明细|长期应收款-长期应收款明细"], "投资性房地产明细", "固定资产明细",
        "在建工程明细", "无形资产明细", "商誉明细", "长期待摊费用明细", "其他非流动资产明细", "短期借款明细", "应付账款明细",
        "预收账款明细|预收款项明细", "长期应付款明细", "其他应付款明细", "长期借款明细", "应付债券明细", "资本公积明细含注|资本公积明细",
        // "营业收入明细", "营业成本明细",
        "营业收入和营业成本明细",
        "财务费用明细", "其他收益明细", "投资收益明细", "营业外收入明细", "营业外支出明细",
        // "现金流量表补充资料",
        ["关联方及关联交易", "关联交易情况|关联方及关联交易-关联交易情况", "其他关联方情况|关联方及关联交易-其他关联方情况", "本企业的子公司情况|关联方及关联交易-本企业的子公司情况", "本企业的母公司情况|关联方及关联交易-本企业的母公司情况", "本企业合营和联营企业情况|关联方及关联交易-本企业合营和联营企业情况"],
        "受限资产明细", "或有事项", "资产负债表日后事项"];
    const [showMenu, setShowMenu] = useState(true) //目录栏是否展示
    const [margin, setMargin] = useState("20px")
    const [isModalVisible, setIsModalVisible] = useState(false);
    const changeContent = useSelector((state: any) => state.ParseResult.changeContent)
    const defaultContent = useSelector((state: any) => state.ParseResult.value)
    const [errorOpen, setErrorOpen] = useState(false)//展开勾稽关系
    const [selectedRowKeys, setSelectedRowKeys] = useState<any>([-100])
    const [selectTitle, setSelectTitle] = useState("")

    const columns = [
        {
            title: '标题',
            dataIndex: 'title',
            key: 'title',
            width: 100,
            onCell: (() => {
                return {
                    style: {
                        innerHeight: "100%",
                        verticalAlign: "text-top"
                    }
                }
            }),
            render: (data: any) => {
                return <div id={data.split("|")[1] ? data.split("|")[1].split("-")[1] || data.split("|")[1].split("-")[0] : data} style={{
                    color: data.split("|")[0] == selectTitle && errorOpen ? "red" : "black"
                }}>{data.split("|")[0]}</div>
            }
        },
        {
            title: '内容',
            dataIndex: 'content',
            key: 'content',
            render: (data: any, info: any) => {
                // console.log(info);

                return <div id={info.title} dangerouslySetInnerHTML={{ __html: data }} style={{ wordWrap: 'break-word', wordBreak: 'break-word' }} ></div>
            },
            width: 380
        },
        {
            title: '操作',
            dataIndex: 'title',
            key: 'edit',
            render: (data: any, info: any) => {
                return <Button type="primary" onClick={() => {

                    setisEditTitle(data.split("|")[1] ? data.split("|")[1] : data.split("|")[0])
                    dispatch(setResultValue(info.content))
                    setIsModalVisible(true)
                }} >编辑</Button>
            },
            width: "20px",
            onCell: (() => {
                return {
                    style: {
                        innerHeight: "100%",
                        verticalAlign: "text-top"
                    }
                }
            })
        },
    ];
    let dataSource: any = []
    keys.forEach((item: any, index: number) => {
        if (typeof item == "string") {
            dataSource.push({
                title: item,
                content: data[item] || "",
                key: item
            })
        } else {
            item.forEach((item: any, index: number) => {
                if (index != 0) {
                    dataSource.push({
                        title: item,
                        content: data[item.split("|")[1]] || "",
                        key: item
                    })
                }
            })
        }
    })
    let errorTitle = dataSource ? dataSource.map(({ title: data }: any) => { return data.split("|")[0] }) : []
    keys.forEach((item: any) => {
        if (typeof item == "string" && item.split("|")[1]) {
            errorTitle.push(item.split("|")[1])
        }
    })
    let list = errorList["财务报表与附注之间"] ? errorList["财务报表与附注之间"].filter((item: any) => errorTitle.indexOf(item.error_key_list[0][0].split("（")[0].split("合计")[0]) != -1) : []
    const errorlist = list ? list.map((item: any, index: number) => {
        return {
            error_info: item.error_info,
            error_key_list: item.error_key_list
            , key: index
        }
    }) : []
    const errorColRef: any = [
        {
            title: "勾稽关系错误",
            dataIndex: "error_info",
            width: 400,
            onHeaderCell: () => {
                return {
                    style: {
                        textAlign: "center"
                    }
                }
            },
            onCell: () => {
                return {
                    style: {
                        fontSize: 13,
                        color: "rgb(96,98,102)"
                    }
                }
            }

        }, {
            dataIndex: "error_key_list",
            title: "相关科目",
            render: (data: any, info: any) => {
                return data.map((item: any, index: number) => {
                    return <Button key={item[0] + item[1]} size={"small"} style={
                        {
                            marginRight: 10,
                            marginBottom: 10,
                            color: "rgb(96,98,102)"
                        }
                    } onClick={(e: any) => {
                        if (index == 0) {
                            let data = ""

                            if (e.target.innerText.indexOf("预付账款账龄") != -1) {
                                data = "预付款项账龄"
                            } else if (e.target.innerText.indexOf("合计") != -1) {
                                data = e.target.innerText.split("合计")[0]


                            } else {
                                data = e.target.innerText.split("（")[0]
                            }

                            setSelectTitle(data == e.target.innerText.split("合计")[0] ? data : e.target.innerText.split("（")[0])
                            let anchorElement = document.getElementById(data);
                            if (anchorElement) {
                                anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
                            }

                        }
                        ;
                    }} >{item[0]} </Button>
                })
            }, onHeaderCell: () => {
                return {
                    style: {
                        textAlign: "center"
                    }
                }
            }

        }
    ]
    const rowSelection = {
        onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {


            setSelectedRowKeys(selectedRowKeys)

        }
    };
    //window监听滚动事件
    window.addEventListener("scroll", (e) => {
        let top = document.documentElement.scrollTop
        let checkTitle = document.getElementById("checktitle")


        if (checkTitle) {
            if (top > 218) {
                (checkTitle as HTMLElement).style.position = "fixed"
                setMargin("305px")
            } else {
                (checkTitle as HTMLElement).style.position = "static"
                setMargin("20px")
            }
        }

    })
    //遮罩层销毁
    const handleCancel = () => {
        setIsModalVisible(false)
        confirm({
            content: "确认关闭HTML编辑器？关闭后不会保存修改",
            onOk() {
                handleOk()
            },
            onCancel() {
                setIsModalVisible(true)
            },
        });
    };
    //确认提交
    const handleOk = async () => {
        if (changeContent) {
            const values: any = {}
            values[isEditTitle] = changeContent
            let params = {
                pperoid: "first",
                projectId,
                data: {
                    kind: "附注",
                    values
                }

            }
            let res = await parseService.updateResult(params)
            if (res.detail = "更新完成") {
                message.success({
                    content: "更新成功",
                    duration: 1
                }).then(() => {
                    window.localStorage.setItem("currentKey", "附注解析")
                    window.location.reload()
                })
            }

        }
        setIsModalVisible(false)
    }
    //点击滚动事件
    const ClickScroll = (item: string) => {
        let anchorElement = document.getElementById(item);
        if (anchorElement) { anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' }); }
    }

    return (
        <div className={styles.helpParse}>
            <div className={styles.Buttonlist}>
                {showMenu ? <Popover content={"收起目录栏"} >
                    <div className={styles.menuButton} onClick={() => {

                        setShowMenu(false)
                    }}><MenuFoldOutlined /></div>
                </Popover> : <Popover content={"展开目录栏"} >
                    <div className={styles.menuButton} onClick={() => {

                        setShowMenu(true)
                    }}><MenuUnfoldOutlined /></div>
                </Popover>}
                {
                    (errorList["财务报表与附注之间"] && errorList["财务报表与附注之间"].length) ? <div style={{
                        marginLeft: showMenu ? "250px" : "50px"

                    }}>
                        {errorOpen ? <Button type="primary" danger onClick={() => {
                            setErrorOpen(false)
                        }}><UpOutlined />收起勾稽关系错误</Button> : <Button type="primary" danger

                            onClick={() => {
                                setErrorOpen(true)
                            }}><DownOutlined />展开勾稽关系错误</Button>}
                    </div> : ""
                }
            </div>
            <div className={styles.titleTree} id="checktitle"
                style={{
                    display: showMenu ? "block" : "none"
                }}>
                {
                    keys.map((item: any, index: number) => {
                        if (typeof item == "string") {
                            return <div key={index}
                                onClick={(e: any) => {

                                    ClickScroll(e.target.innerText)
                                }}
                                className={styles.normalText}


                            >{item.split("|")[1] ? item.split("|")[1] : item.split("|")[0]}</div>
                        } else {
                            let title = item.filter((item: any, index: number) => index != 0)
                            return <Collapse bordered={false} className={styles.Collapse} key={index} >
                                <Panel header={item[0]} key={index} >
                                    {
                                        title.map((item: any, index: any) => {
                                            return <div key={index} className={"normalText"}
                                                onClick={(e: any) => {
                                                    ClickScroll(e.target.innerText)
                                                }}
                                            >{item.split("|")[1] ? item.split("|")[1].split("-")[1] : item.split("|")[0]}</div>
                                        })
                                    }
                                </Panel>

                            </Collapse>
                        }
                    })
                }
            </div>
            {errorList["财务报表与附注之间"] && errorList["财务报表与附注之间"].length && errorOpen ? <div style={{
                marginLeft: showMenu ? margin : 100,
                width: 900,
                float: "left",
                marginBottom: 20
            }}>
                <Table
                    bordered={true}
                    scroll={{ y: 300 }}
                    rowSelection={{
                        selectedRowKeys,
                        type: 'radio',
                        ...rowSelection,
                    }}
                    onRow={(record: any) => ({
                        onClick: (e) => {
                            if (record.key != selectedRowKeys) {
                                // console.log(record);
                                let data = ""

                                if (record.error_key_list[0][0].indexOf("预付账款账龄") != -1) {
                                    data = "预付款项账龄"
                                } else if (record.error_key_list[0][0].indexOf("合计") != -1) {
                                    data = record.error_key_list[0][0].split("合计")[0]


                                } else {
                                    data = record.error_key_list[0][0].split("（")[0]
                                }

                                setSelectTitle(data == record.error_key_list[0][0].split("合计")[0] ? data : record.error_key_list[0][0].split("（")[0])
                                let anchorElement = document.getElementById(data);
                                if (anchorElement) {
                                    anchorElement.scrollIntoView({ block: 'start', behavior: 'smooth' });
                                }
                                setSelectedRowKeys([record.key])
                            }

                        }
                    })}
                    pagination={false}
                    columns={errorColRef}
                    dataSource={errorlist}
                />
            </div> : ""}
            <div className={styles.parseResult} style={{ marginLeft: showMenu ? margin : 100 }}>
                <Table
                    bordered={true}
                    dataSource={dataSource} columns={columns} pagination={false} showHeader={false} />
            </div>
            <Modal
                title="编辑"
                okText="确认"
                cancelText="取消"
                destroyOnClose={true}
                visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}
                width={"1000px"}
                bodyStyle={{ minHeight: "500px", width: "1000px" }}>
                < ReactQuill ></ReactQuill>
            </Modal>
        </div>
    )
}
